//
//  xinxiViewController.m
//  tongxiangOASystem
//
//  Created by michael on 2018/4/25.
//  Copyright © 2018年 czd. All rights reserved.
//
#import "LGLSearchBar.h"
#import "FSwaitdetailViewController.h"
#import "ggxqViewController.h"
#import "yiyuewenjianViewController.h"
#import "LGLSearchBar.h"
#import "daibanTableViewCell.h"
#import "detailViewController.h"
#import "yjTableViewCell.h"
#import "dzTableViewCell.h"
#import "GDataDefines.h"
#import "UnDoneModel.h"
#import "OADetailViewController.h"
#import "OADetailDisPatchController.h"
#import "OAUnDoneListCell.h"
#import "ckUnDonelistCell.h"
#import "dzggViewController.h"
#import "xinxiViewController.h"
#import "PTLMenuButton.h"
#import "PTLMaskingView.h"

@interface xinxiViewController ()<PTLMenuButtonDelegate>
@property(nonatomic,strong)NSMutableArray * dataArray;
@property(nonatomic,assign)int totalCounts; //总条数
@property(nonatomic,assign)int currentPage; //当前页
@property(nonatomic,strong)NSDictionary * adic;
@property (nonatomic,strong)NSString *searchstr;
@property (nonatomic,strong)NSString *isSearching;
@property (nonatomic, strong) NSArray *yearArray;
@property (nonatomic, strong) NSArray *bumenArray;

@property (nonatomic, strong) NSArray *nameArray;

@property (nonatomic, assign) NSInteger year;
@property (nonatomic, assign) NSString* yearstring;
@property (nonatomic, assign) NSString* bumenstring;
@property (nonatomic, assign) NSString* nametring;
@property (nonatomic,strong)PTLMenuButton *btn;

@end

@implementation xinxiViewController

- (void)viewDidLoad {
    [super viewDidLoad];
      NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute fromDate:[NSDate date]];
    _year = [components year];
//    _yearstring = [NSString stringWithFormat:@"%ld",(long)_year];
// NSInteger firstYear = 2018;
    NSMutableArray *yearArray = [NSMutableArray array];
    for (int i = 0; i <= _year-2013; i++) {
        [yearArray addObject:[NSString stringWithFormat:@"%ld", _year - i]];
    }
    _yearArray = yearArray;
     self.view.backgroundColor = [UIColor colorWithHexString:@"efeff4"];
 LGLSearchBar * searchBar = [[LGLSearchBar alloc] initWithFrame:CGRectMake(0, 10, KScreenWidth, 40) searchBarStyle:LGLSearchBarStyleDefault];
[searchBar setSearchBarBordeWidth:0.1 bordColor:[UIColor clearColor] bordRadius:0];
//[searchBar setSearchBarImage:@"search" scale:30];
        [searchBar searchBarTextSearchTextBlock:^(NSString *searchText) {
        NSLog(@"%@", searchText);
        if (searchText.length>0) {
        
            if (!(self.bumenstring.length>0)) {
    [self.view makeToast:@"部门不能为空"];

}else if(!(self.nametring.length>0)) {
    [self.view makeToast:@"名称不能为空"];

}else if(!(self.yearstring.length>0)) {
    [self.view makeToast:@"年限不能为空"];

}else{
    
        _isSearching = @"yes";
    _searchstr = searchText;
  [_tableView headerBeginRefreshing];

//        [self loadSearchData];
}
      
}
        else{
[self.view makeToast:@"搜索关键字不能为空"];
}

    }];
  
//    [self.view addSubview:searchBar];
    [self requestdata];
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth,self.view.height-kTopHeight-0-LL_TabbarSafeBottomMargin) style:UITableViewStylePlain];

//    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 50+5+30, KScreenWidth,self.view.height-kTopHeight-55-30-LL_TabbarSafeBottomMargin) style:UITableViewStylePlain];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.tableView.backgroundColor = [UIColor colorWithHexString:@"efeff4"];

_tableView.dataSource = self;
_tableView.delegate = self;
[self.view addSubview:_tableView];
                 __weak typeof(self) weakSelf = self;

[self.tableView addHeaderWithCallback:^{

if(self.tableView.headerRefreshing)
{


}else{
        weakSelf.currentPage = 1;
         if ([weakSelf.isSearching isEqualToString:@"yes"]) {
     [weakSelf loadSearchData];
}else{
NSLog(@"1111");
        [weakSelf loadData]; //加载网络数据

}
}
    }];
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];

    [self.tableView headerBeginRefreshing];
    
    [self.tableView addFooterWithCallback:^{
        if ((weakSelf.currentPage - 1)*KPageSize < weakSelf.totalCounts ){
        if ([weakSelf.isSearching isEqualToString:@"yes"]) {
     [weakSelf loadSearchMore];
}
     else {
     [weakSelf loadMore];
     }
        }else{
            
            [weakSelf.tableView footerEndRefreshing];
            [weakSelf.view makeToast:@"没有更多了"];
            
        }
        
    }];
    // Do any additional setup after loading the view.
}

-(void)refreshData{
    
    self.currentPage = 1;
    [self loadData]; //加载网络数据
}
- (void)requestdata{
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"userId":userId}];
     [HttpTools requestWithURL:KexchxxjbURL arrays:array method:@"xxjbbm" success:^(id JSON) {
     NSMutableArray *array =  [NSMutableArray array];
NSArray *array1 = JSON[@"data"];
for (NSDictionary *dic in array1) {
    [array addObject:dic[@"bm"]];
}
self.bumenArray  = array;
     [self requestdata2];
  
         NSLog(@"%@",JSON);
 } failure:^(NSError *error) {
     
    }];
}
- (void)requestdata2{
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"userId":userId}];
     [HttpTools requestWithURL:KexchxxjbURL arrays:array method:@"xxjbtype" success:^(id JSON) {
         NSLog(@"%@",JSON);
     NSMutableArray *array =  [NSMutableArray array];
NSArray *array1 = JSON[@"data"];
for (NSDictionary *dic in array1) {
    [array addObject:dic[@"type"]];
}
self.nameArray  = array;
//     [self initview];
 } failure:^(NSError *error) {
     
    }];
}
- (void)initview{
if (_btn) {
[_btn removeFromSuperview];
}    _btn = [[PTLMenuButton alloc]initWithFrame:CGRectMake(0, 55, self.view.frame.size.width, 30) menuTitles:@[@"年度",@"部门",@"名称"]];
    NSMutableArray *listarray1 = [NSMutableArray array];
listarray1 = [_bumenArray mutableCopy];

if (_bumenstring.length>0) {
[listarray1 insertObject:[NSString stringWithFormat:@"%@%@",@"当前选择:",_bumenstring] atIndex:0];
//        [listarray1 addObject:];


}else{

}
 NSMutableArray *listarray2 = [NSMutableArray array];
listarray2 = [_nameArray mutableCopy];
if (_nametring.length>0) {
[listarray2 insertObject:[NSString stringWithFormat:@"%@%@",@"当前选择:",_nametring] atIndex:0];


}
 NSMutableArray *listarray3 = [NSMutableArray array];
listarray3 = [_yearArray mutableCopy];
if (_yearstring.length>0) {
[listarray3 insertObject:[NSString stringWithFormat:@"%@%@",@"当前选择:",_yearstring] atIndex:0];


}
 NSArray * listArr1 = listarray1;
    NSArray * listArr2 = listarray2;
    NSArray * listArr3 = listarray3;

  _btn.listTitles = @[listArr3,listArr1, listArr2];
    _btn.delegate = self;
    [self.view addSubview:_btn];
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 29, self.view.frame.size.width, 1)];
    view.backgroundColor = [UIColor colorWithHexString:@"f0eff5"];
//        [self.view addSubview:view];
     __weak typeof(self) weakSelf = self;

  [self.btn.listView.maskingView setButtonblock :^() {
  NSLog(@"11111");
 self.nametring = @"";
self.bumenstring = @"";
self.yearstring = @"";
    _isSearching = @"no";
    [self.tableView headerBeginRefreshing];
//     [self initview];


  }];




}
-(void)ptl_menuButton:(PTLMenuButton *)menuButton didSelectMenuButtonAtIndex:(NSInteger)index selectMenuButtonTitle:(NSString *)title listRow:(NSInteger)row rowTitle:(NSString *)rowTitle{
 if ([rowTitle isEqualToString:@"清空搜索条件"]){
    _nametring = @"";
    _bumenstring = @"";
    _yearstring = @"";


    }else if ([rowTitle containsString:@"当前选择:"]){
    return;
    }


    if ([title isEqualToString:@"部门"]){
_bumenstring = rowTitle;
     [self initview];


}else if ([title isEqualToString:@"名称"]){
_nametring  = rowTitle;
     [self initview];


}else if ([title isEqualToString:@"年度"]){
_yearstring  = rowTitle;
     [self initview];


}


}
- (void)loadSearchData{
    __weak typeof(self) weakSelf = self;
_currentPage = 1;
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"year":_yearstring},@{@"type":_nametring},@{@"bm":_bumenstring},@{@"condition":_searchstr},@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
     [HttpTools requestWithURL:KexchxxjbURL arrays:array method:@"xxjbsearch" success:^(id JSON) {
    NSLog(@"%@",JSON);

      if (self.currentPage ==1) {
            [self.dataArray removeAllObjects];
        }
      _dataArray =   [NSMutableArray array];
        NSArray *array = JSON[@"data"];
                self.totalCounts =[JSON[@"number"] intValue];
if(JSON[@"number"]){
_titlename = [NSString stringWithFormat:@"信息简报(%@)",JSON[@"number"] ];
   if (self.selectRowBlock) {
  self.selectRowBlock(_titlename);
  }
}else{
_titlename  = @"信息简报";
  if (self.selectRowBlock) {
  self.selectRowBlock(_titlename);
  }
}
         for (NSDictionary *dic in array) {
    NSDictionary *dict = dic;
    [_dataArray addObject:dict];
    
}
_adic= JSON[@"display"];

        [weakSelf.tableView footerEndRefreshing];
        [weakSelf.tableView reloadData];
        weakSelf.currentPage++;
        
        if (self.tableView.headerRefreshing) {
            [self.tableView headerEndRefreshing];
        }
        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
        
    } failure:^(NSError *error) {
        if (self.tableView.headerRefreshing) {
            [self.tableView headerEndRefreshing];
        }
        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
    }];

}
- (void)loadSearchMore{
    __weak typeof(self) weakSelf = self;

NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"year":_yearstring},@{@"type":_nametring},@{@"bm":_bumenstring},@{@"condition":_searchstr},@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
 [HttpTools requestWithURL:KexchxxjbURL arrays:array method:@"xxjbsearch" success:^(id JSON) {

       NSArray *array = JSON[@"data"];

 for (NSDictionary *dic in array) {
    NSDictionary *dict = dic;
    [_dataArray addObject:dict];
    
}
_adic= JSON[@"display"];

   self.totalCounts =[JSON[@"number"] intValue];


        [weakSelf.tableView footerEndRefreshing];
        [weakSelf.tableView reloadData];
        weakSelf.currentPage++;

        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
     
    } failure:^(NSError *error) {

        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
    }];
}
- (void)viewWillAppear:(BOOL)animated{

// if (self.selectRowBlock) {
//  self.selectRowBlock(_titlename);
//  }
    [self.tableView headerBeginRefreshing];
_isSearching = @"no";
}
#pragma mark 加载网络数据
-(void)loadData{
//    [MBProgressHUD showHUDAddedTo:self.view animated:YES];

    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    //requestWithURL
    [HttpTools requestWithURL:KexchxxjbURL arrays:array method:@"xxjb" success:^(id JSON) {
              [MBProgressHUD hideAllHUDsForView:self.view animated:YES];

    NSLog(@"%@",JSON);
        if (self.currentPage ==1) {
           [self.dataArray removeAllObjects];
        }

  self.dataArray =   [NSMutableArray array];
        NSArray *array = JSON[@"data"];
        self.totalCounts =[JSON[@"number"] intValue];
         if(JSON[@"number"]){

     self.title = [NSString stringWithFormat:@"信息简报(%@)",JSON[@"number"] ];
    
       }
        else{

       self.title  = @"信息简报";
     
       }
     
self.adic= JSON[@"display"];

         for (NSDictionary *dic in array) {
    NSDictionary *dict = dic;
    [self.dataArray addObject:dict];
    
}

        [self.tableView reloadData];
    if (self.tableView .headerRefreshing) {
            [self.tableView headerEndRefreshing];

}        self.currentPage++;
        if (self.dataArray.count ==0) {
        [self.view makeToast:@"暂时还没有信息简报哦"];
        }
    } failure:^(NSError *error) {
              [MBProgressHUD hideAllHUDsForView:self.view animated:YES];

    if (self.tableView .headerRefreshing) {
            [self.tableView headerEndRefreshing];

}
    }];
 
}
#pragma mark 加载更多
-(void)loadMore{
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    [HttpTools requestWithURL:KexchxxjbURL arrays:array method:@"xxjb" success:^(id JSON) {
        NSArray *array = JSON[@"data"];

  for (NSDictionary *dic in array) {
    NSDictionary *dict = dic;
    [_dataArray addObject:dict];
    
}
_adic= JSON[@"display"];

        self.currentPage++;
                [self.tableView reloadData];

        [self.tableView footerEndRefreshing];
       
    } failure:^(NSError *error) {
         [self.tableView footerEndRefreshing];
    }];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

     NSDictionary *dic = self.dataArray[indexPath.row];

    CGFloat  titleFloat  = [OAToolBox sizebyText:dic[@"subject"] font:14 minsWidth:60];

    return  titleFloat+10+10+20;


}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

 static NSString *CellIdentifier = @"Cell";

    daibanTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
  if (cell==nil) {
        cell=[[daibanTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
 NSDictionary *dic = self.dataArray[indexPath.row];
    cell.dic = dic;
    cell.adic = _adic;
    cell.number = [NSString stringWithFormat:@"%ld",(long)indexPath.row+1];
    return cell;


 }
 -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

      UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
        NSDictionary *dic = self.dataArray[indexPath.row];

     UnDoneModel * model = self.dataArray[indexPath.row];
     detailViewController * detailVC = (detailViewController *)[storyBoard instantiateViewControllerWithIdentifier:@"detail"];
//     ggxqViewController * detailVC = (ggxqViewController *)[storyBoard instantiateViewControllerWithIdentifier:@"ggxq"];
detailVC.fileId = dic[@"unid"];
detailVC.type = @"xxjb";

[self.navigationController pushViewController:detailVC animated:YES];
}
@end


